package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Map;

@Component
public class OrderReceiver {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentFeignClient paymentFeignClient;

    //监听取消订单 paymentInfo更新状态后的消息
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId, Message message, Channel channel){
        try {
            if (orderId!=null){
                OrderInfo orderInfo = orderService.getById(orderId);
                if(orderInfo!=null && "UNPAID".equals(orderInfo.getOrderStatus()) && "UNPAID".equals(orderInfo.getProcessStatus())){
                    //取消订单 关闭相应的paymentInfo和alipay
                    //先判断paymentInfo是否存在
                    PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                    if(paymentInfo!=null && "UNPAID".equals(paymentInfo.getPaymentStatus())){
                        Boolean result = paymentFeignClient.checkPayment(orderId);
                        if (result){ //如果为true，说明已经扫码，但是未支付
                            //调用支付宝接口，关闭订单
                            Boolean flag = paymentFeignClient.closePay(orderId);
                            if (flag){//说明已经关闭了支付宝内部的交易记录
                                //还需要关闭paymentInfo和orderInfo
                                orderService.execExpiredOrder(orderId,"2");
                            }else {//说明已经付款，无法取消订单，走异步通知

                            }
                        }else {//说明还没扫码，支付宝内部还没有交易记录，只需要关闭paymentInfo和orderInfo即可
                            orderService.execExpiredOrder(orderId,"2");
                        }
                    }else {//payment不存在，只需关闭orderInfo即可
                        orderService.execExpiredOrder(orderId,"1");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //监听支付之后的的消息
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
                                            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
                                            key = {MqConst.ROUTING_PAYMENT_PAY}))
    public void updateOrder(Long orderId, Message message, Channel channel){
        try {
            if(orderId!=null){
                //更新订单状态
                orderService.updateOrderStatus(orderId,ProcessStatus.PAID);
                // TODO: 2022/2/15  通知库存系统
                orderService.sendOrderStatus(orderId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //扣减库存，更新订单状态
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
                                            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
                                            key = {MqConst.ROUTING_WARE_ORDER}))
    public void updateOrderStatus(String jsonStr,Message message,Channel channel){
        if(!StringUtils.isEmpty(jsonStr)){
            Map<String,Object> paramMap = JSON.parseObject(jsonStr, Map.class);
            String orderId = (String) paramMap.get("orderId");
            String status = (String) paramMap.get("status");
            if("DEDUCTED".equals(status)){
                //更新订单状态
                orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.WAITING_DELEVER);
            }else {
                orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.STOCK_EXCEPTION);
            }
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
